package cn.max.web.filters;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.max.SystemConstants;

public class LoginFilter implements Filter {
	
	private List<String> ignoreUris = new ArrayList<String>();

	public LoginFilter() {}

	public void destroy() {}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		HttpSession session = req.getSession();

		Object user = session.getAttribute(SystemConstants.USER);
		
		//3 min
//		Object timestamp = session.getAttribute(SystemConstants.TIMESTAMP);
//		if (timestamp == null || new Date().getTime() - Long.parseLong(timestamp.toString()) > 3 * 60000) {
//			res.sendRedirect(req.getContextPath() + "/login.jsp");
//			return;
//		}
		
		if (user != null) {
			chain.doFilter(request, response);
			return;
		}

		String uri = req.getRequestURI().toLowerCase();

		if (uri.matches("[\\w\\/-]+\\.(css|js|jpg|jpeg|png|gif|jar|ico|htc|swf|json)")) {
			chain.doFilter(request, response);
			return;
		}
		uri = uri.substring(req.getContextPath().length() + 1);
		
		for (String regex : ignoreUris) {
			if (uri.matches(regex)) {
				chain.doFilter(request, response);
				return;
			}
		}
		res.sendRedirect(req.getContextPath() + "/login.jsp");
	}
	
	public void init(FilterConfig fConfig) throws ServletException {
		
		String ignoreUriStr = fConfig.getInitParameter("ignore-uris");
		
		if (ignoreUriStr == null) {
			throw new RuntimeException("init-param <ignore-uris> should be configured for this filter!");
		}
		
		for (String s : ignoreUriStr.split(",")) {
			ignoreUris.add(parseAsRegex(s));
		}
		
	}
	
	private static String parseAsRegex(String s) {
		if (s.indexOf('*') == -1) {
			return s;
		}
		
		return s.replaceAll("\\*\\*", "[_\\\\-\\\\d\\\\w./]+").replaceAll("\\*", "[_\\\\-\\\\d\\\\w/]+");
	}

}
